-module(mhelper).

-export([parse_transform/2]).

parse_transform(Forms, _) ->
    %%forms(Forms).
    F2 = forms(Forms),
  %  io:format("~p~n", [F2]),
    my_pp:print(F2, "mhelper.txt", true),
    F2.

forms([F|Forms]) ->
    F2 = form(F),
    Forms2 = forms(Forms),
    [F2|Forms2];
forms([]) ->
    [].

form({function, Line1, Name, Arity, Clauses}) ->
    Clauses2 = clauses(Clauses),
    {function, Line1, Name, Arity, Clauses2};

form(F) ->
    F.

clauses([C|Clauses]) ->
    C2 = clause(C),
    Clauses2 = clauses(Clauses),
    [C2|Clauses2];
clauses([]) ->
    [].

clause({clause, Line2, Args, [[{call,_,{atom,_,'DO_TRANSFORM'}, [{integer, _, Times}]}]], Exprs}) ->
    {MultiExprs, EndExprs} = splitExprs(Exprs),
    {clause, Line2, Args, [], multiple(  Times, EndExprs, MultiExprs)};
clause(C) ->
    C.

splitExprs([]) ->
    throw("missing 'END_TRANSFORM_BLOCK'");
splitExprs([{atom, _, 'END_TRANSFORM_BLOCK'}|Exprs]) ->
    {[], Exprs};
splitExprs([Expr|Exprs]) ->
    {MultiExprs, EndExprs} = splitExprs(Exprs),
    {[Expr|MultiExprs], EndExprs}.


multiple(0, L, _) ->
    L;
multiple(N, L, Exprs) when is_integer(N) andalso N > 0 ->
    L2 = Exprs++L,
    multiple(N-1, L2, Exprs).